package org.nw;

import java.io.InputStream;
import java.util.Properties;

import org.nw.utils.PropertiesUtils;


/**
 * 全局配置文件
 * 
 * @author xuqc
 * 
 */
public class Global {
	private static Properties prop = null;
	private static String fileName = "/nw.properties";
	private static String resourveVersionFile = "/resource.version";
	private static String version = null;

	// 上传文件的根路径
	public static String uploadDir;
	static {
		if(Global.prop == null) {
			Global.prop = PropertiesUtils.loadProperties(Global.class.getResourceAsStream(fileName));
		}
		uploadDir = getPropertyValue("upload.dir");
	}

	/**
	 * 加载配置文件
	 * 
	 * @return
	 */
	public static Properties getProp() {
		if(Global.prop == null) {
			Global.prop = PropertiesUtils.loadProperties(Global.class.getResourceAsStream(fileName));
		}
		return Global.prop;
	}

	/**
	 * 根据key返回某个配置项的值
	 * 
	 * @param key
	 * @return
	 */
	public static String getPropertyValue(String key) {
		if(prop == null) {
			prop = getProp();
		}
		try {
			String value = prop.getProperty(key);
			if(value != null) {
				value = value.trim();
			}
			return value;
		} catch(Exception e) {

		}
		return null;
	}

	public static int getIntValue(String key) {
		String value = getPropertyValue(key);
		int iValue = 0;
		try {
			iValue = Integer.parseInt(value);
		} catch(Exception e) {
		}
		return iValue;
	}

	public static boolean getBooleanValue(String key) {
		String value = getPropertyValue(key);
		boolean bValue = false;
		try {
			bValue = Boolean.parseBoolean(value);
		} catch(Exception e) {
		}
		return bValue;
	}

	/**
	 * 返回
	 * 
	 * @return
	 */
	public static String getResourceVersion() {
		if(version == null) {
			StringBuffer sb = new StringBuffer();
			try {
				InputStream in = Global.class.getResourceAsStream(resourveVersionFile);
				int n;
				while((n = in.read()) != -1) {
					sb.append((char) n);
				}
				in.close();
				version = sb.toString();
			} catch(Exception e) {
				e.printStackTrace();
				throw new RuntimeException("读取资源版本时出错，出错信息：" + e.getMessage());
			}
			if(version == null || version.length() == 0) {
				throw new RuntimeException("没有读取到资源版本号，请检查配置文件resource.version！");
			}
		}
		return version;
	}
}
